package com.salesmanager.web.admin.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.salesmanager.core.business.system.model.SystemConfiguration;
import com.salesmanager.core.business.system.service.SystemConfigurationService;
import com.salesmanager.license.util.LicenseUtil;

@Controller
public class LicenseController {

	@Autowired
	protected SystemConfigurationService systemConfigurationService;

	@RequestMapping(value = "/license/display.html", method = RequestMethod.GET)
	public String displayLisence(Model model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		model.addAttribute("uniqueKey", LicenseUtil.getKey());
		return "admin/license";
	}

	@RequestMapping(value = "/license/save.html", method = RequestMethod.GET)
	public String saveLisence(@RequestParam("j_license") String license, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		//String license = (String) request.getAttribute("j_license");
		SystemConfiguration systemConfiguration = systemConfigurationService
				.getByKey("license");
		if (systemConfiguration != null) {
			systemConfiguration.setValue(license);
			systemConfigurationService.update(systemConfiguration);
		} else {
			systemConfiguration = new SystemConfiguration();
			systemConfiguration.setKey("license");
			systemConfiguration.setValue(license);

			systemConfigurationService.create(systemConfiguration);
		}

		return "redirect:/admin/logon.html";
	}

}
